import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, Optional } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzTabChangeEvent } from 'ng-zorro-antd/tabs';
import {AuthService} from "@core/service/AuthService";
import {UserInfo} from "@shared/models/UserInfo";

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoginComponent implements OnDestroy {
  constructor(
    fb: FormBuilder,
    private router: Router,
    @Optional()
    private cdr: ChangeDetectorRef,
    private authService:AuthService
  ) {
    this.form = fb.group({
      account: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z_@.]*$/)]],
      password: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z_.@]*$/)]],
      mail: [null, [Validators.required, Validators.email]],
      captcha: [null, [Validators.required]],
      remember: [true]
    });
  }

  // #region fields

  get account(): AbstractControl {
    return this.form.controls.account;
  }
  get password(): AbstractControl {
    return this.form.controls.password;
  }
  get mail(): AbstractControl {
    return this.form.controls.mail;
  }
  get captcha(): AbstractControl {
    return this.form.controls.captcha;
  }
  get remember(): AbstractControl {
    return this.form.controls.remember;
  }
  form: FormGroup;
  error = '';
  type = 0;
  loading = false;

  // #region get captcha

  count = 0;
  interval$: any;

  // #endregion

  switch({ index }: NzTabChangeEvent): void {
    this.type = index!;
  }

  getCaptcha(): void {
    if (this.mail.invalid) {
      this.mail.markAsDirty({ onlySelf: true });
      this.mail.updateValueAndValidity({ onlySelf: true });
      return;
    }
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) {
        clearInterval(this.interval$);
      }
    }, 1000);
  }

  // #endregion

  submit(): void {
    this.error = '';
    let that = this;

    let data;
    let keepSecond = 600;
    if (this.remember.value){
      keepSecond = 3600*24*15;
    }

    if (this.type === 0) {
      this.account.markAsDirty();
      this.account.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.account.invalid || this.password.invalid) {
        return;
      }
      data = {
        account:that.account.value,
        password:that.password.value,
        keepSecond
      }
    } else {
      this.mail.markAsDirty();
      this.mail.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mail.invalid || this.captcha.invalid) {
        return;
      }
      data = {
        email:that.mail.value,
        captcha:that.captcha.value,
        keepSecond
      }
    }
    this.loading = true;
    this.cdr.detectChanges();
    console.log(data)
    this.authService
      .login(this.type,data)
        .subscribe(
        (res: any) => {
          console.log(res)
          if (res.code==200){
            localStorage.setItem('token', res.data.token);
            that.authService.saveLoginStatus(res.data);
            that.authService.userInfo = res.data.userInfo
            that.router.navigate(['/myDisk']);
          }else {
            that.error = res.msg;
          }
          that.loading = false;
          this.cdr.detectChanges();
        },
        (error:any) => {
          console.log(error)
          that.error = '连接失败,请检查网咯！';
          that.loading=false;
          this.cdr.detectChanges();
        }
      );
  }

  // #endregion

  ngOnDestroy(): void {
    if (this.interval$) {
      clearInterval(this.interval$);
    }
  }
}
